/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Force-TLS.
 *
 * The Initial Developer of the Original Code is
 * Sid Stamm.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */
/*
 * Change Log:
 * v4.0   (2/21/2014):
 *   <sid>: removed logic for custom back-end.  (Issue 22).
 * v2.0 (9/2/2009):
 *   <sid>: Added first-run page that explains how to upgrade hard coded rules.
 */

var gFTLSUpgradeURL  = "chrome://forcetls/content/upgrade.html";
var gFTLSFirstrunURL  = "chrome://forcetls/content/firstrun.html";
var gFTLSFirstrunOldURL  = "chrome://forcetls/content/firstrun-old.html";

var forcetls = {
  getAddonVersion:
  function(callback) {
    // gecko 1.9.x
    if (typeof(Cc['@mozilla.org/extensions/manager;1']) != 'undefined') {
      var extMgr =  Cc["@mozilla.org/extensions/manager;1"]
                              .getService(Ci.nsIExtensionManager);
      callback(extMgr.getItemForID('forcetls@sid.stamm').version);
    }
    // gecko 2.0
    else if (typeof(Components.utils) != 'undefined' && typeof(Components.utils.import) != 'undefined') {
       Components.utils.import("resource://gre/modules/AddonManager.jsm");
       AddonManager.getAddonByID('forcetls@sid.stamm', function(addon) {
           callback(addon.version);
       });
    }
  },

  onLoad:
  function() {
    var prefSvc = Cc["@mozilla.org/preferences-service;1"]
                            .getService(Ci.nsIPrefService);
    Components.utils.import("resource://forcetls/ForceTLSUtils.jsm");

    forcetls.ver = -1;
    forcetls.firstrun = true;
    forcetls.initialized = true;
    forcetls.hasMigrated = false;
    forcetls.strings = document.getElementById("forcetls-strings");
    forcetls.prefs = prefSvc.getBranch("extensions.forcetls@sid.stamm.");

    // get flattened list of pref names
    var preflist={};
    for (var i=0; i<forcetls.prefs.length; i++) {
      preflist[forcetls.prefs[i]]='';
    }

    // Check for first-run and upgrade
    try {
	forcetls.ver = forcetls.prefs.getCharPref("version");
	forcetls.firstrun = forcetls.prefs.getBoolPref("firstrun");
    }
    catch(e){}
    finally{
      FTLSDebug("Checking for upgrades and stuff");
      var win = window;
      forcetls.getAddonVersion(function(currentVersion) {
          FTLSDebug("Grabbing addon version " + currentVersion);
          if (forcetls.firstrun) {
            FTLSDebug("Executing first run.");
            
            /**********
            // Uncomment to install toolbar button next to bookmarks button and menu button
            var toolbar = document.getElementById("nav-bar");
            toolbar.insertItem("ftlsbutton", null);
            toolbar.setAttribute("currentset", toolbar.currentSet);
            document.persist(toolbar.id, "currentset");
            **********/
            
            //new install!
            // show first run info
            win.setTimeout(function(){
              // check for Australis:
              if (document.getElementById("PanelUI-menu-button")) {
                gBrowser.selectedTab = gBrowser.addTab(gFTLSFirstrunURL);
              } else {
                gBrowser.selectedTab = gBrowser.addTab(gFTLSFirstrunOldURL);
              }
            }, 1500);
          } else {
            FTLSDebug("Executing upgrade run.");
            //not first run, but could be an upgrade
            if (forcetls.ver != currentVersion) {
              var previousMajorVersion = forcetls.ver.split('.')[0];
              if(previousMajorVersion < 2) {
                // upgrade from version 1
                forcetls.migrateHardcodedRules();
              }
              else if (previousMajorVersion < 4) {
                // upgrade from version 2 or 3
                // Nothing special to do.
              }
              // Put minor 4.x upgrades here.

              // show upgrade info
              win.setTimeout(function(){
                gBrowser.selectedTab = gBrowser.addTab(gFTLSUpgradeURL);
              }, 1500);
            }
          }
          forcetls.prefs.setBoolPref("firstrun",false);
          forcetls.prefs.setCharPref("version",currentVersion);
      });
    }
    window.removeEventListener("load",function(e){ forcetls.onLoad(e); },false);
  },

  migrateHardcodedRules:
  function() {
    Components.utils.import("resource://forcetls/ForceTLSUtils.jsm");

    try { 
      //read in hard-coded rules
      var prefSvc = Cc["@mozilla.org/preferences-service;1"]
                              .getService(Ci.nsIPrefService);
      var hardcoded = prefSvc.getBranch("extensions.forcetls@sid.stamm.permanant.");
      hardcoded.QueryInterface(Ci.nsIPrefBranch2);

      var rules = hardcoded.getChildList('rule', {});

      for each (var rule in rules) {
        var host = rule.substring(5);
        var includesubdomains = false;
        try { // don't completely die if the 'subd' pref is omitted 
          includesubdomains = hardcoded.getBoolPref('subd.' + host);
        } catch(e) {}

        // activate the force-tls policy for this host for more than a year
        var theURI = Cc["@mozilla.org/network/io-service;1"]
                       .getService(Ci.nsIIOService)
                       .newURI("https://"+host, null, null);
        var ftlss = Cc["@sidstamm.com/forcetls;1"].createInstance(Ci.IForceTLS);
        ftlss.setStsState(theURI, includesubdomains, 32000000, 
                          Ci.nsIPermissionManager.EXPIRE_NEVER);

        FTLSDebug("Migrated hardcoded rule to STS backend: " + host + " - " + hdr );
      }

      //delete prefs
      var r = hardcoded.deleteBranch("");
    } catch(e) {
      FTLSDebug("Couldn't migrate rules: " + e);
    }
  },

  setPreferences:
  function(ref, event) {
    var strings = document.getElementById("forcetls-strings");
    var params = { forceVisible: true, prefilledHost: "", permissionType: "forcetls"};
    params.windowTitle = strings.getString("prefWindowTitle");
    params.introText = strings.getString("prefWindowIntro");
    window.openDialog("chrome://forcetls/content/forcedsites.xul",
                      "_blank", "resizable,dialog=no,centerscreen",params);
  },

  ///////// for AddonListener: /////////////
  onUninstalling:
  function(addon) {
    if (addon.id == "forcetls@sid.stamm") {
      // reset prefs
      var prefSvc = Cc["@mozilla.org/preferences-service;1"]
                      .getService(Ci.nsIPrefService);
      prefSvc.getBranch("extensions.forcetls@sid.stamm.")
             .setBoolPref("firstrun",true);
    }
  },

  onOperationCancelled:
  function(addon) { },

};

try {
  Components.utils.import("resource://gre/modules/AddonManager.jsm");
  AddonManager.addAddonListener(forcetls);
} catch(ex) { }

window.addEventListener("load", function(e) { forcetls.onLoad(e); }, false);
